package com.glsc.ngateway.opmanage.controller.archive;

import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.archive.ArchiveClient;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.archive.ArchiveFileInfo;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.archive.CounterParty;
import com.glsc.ngateway.common.base.dto.opmanage.report.archive.ArchiveClientOrgDto;
import com.glsc.ngateway.opmanage.dto.*;
import com.glsc.ngateway.opmanage.service.archive.ArchiveService;
import com.glsc.ngateway.opmanage.service.archive.CounterPartyService;
import com.glsc.ngateway.opmanage.utils.report.ReportFileConfigEnum;
import com.glsc.ngateway.opmanage.utils.report.ReportFileUtil;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 档案中心
 */
@RestController
@RequestMapping("/api/archive")
@Slf4j
public class ArchiveController {

    @Resource
    private ArchiveService archiveService;

    @Resource
    private CounterPartyService counterPartyService;


    /**
     * 分页查询客户列表信息
     *
     * @param clientId
     * @param
     * @param businessLicenseCode
     * @param contactPersonName
     * @param telephone
     * @param mobile
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/client/page")
    public PlatformResponse<Page<ArchiveClient>> findClientPage(@ApiParam(value = "客户编号") @RequestParam(required = false) String clientId,
                                                                @ApiParam(value = "客户名称") @RequestParam(required = false) String clientName,
                                                                @ApiParam(value = "营业执照编码") @RequestParam(required = false) String businessLicenseCode,
                                                                @ApiParam(value = "联系人姓名") @RequestParam(required = false) String contactPersonName,
                                                                @ApiParam(value = "联系人电话") @RequestParam(required = false) String telephone,
                                                                @ApiParam(value = "联系人手机") @RequestParam(required = false) String mobile,
                                                                @ApiParam(value = "交易对手方名称") @RequestParam(required = false) String partyName,
                                                                @ApiParam(value = "交易对手方组织机构代码") @RequestParam(required = false) String partyOrganCode,
                                                                @ApiParam(value = "页码从1开始") @RequestParam(required = false) Integer pageNo,
                                                                @ApiParam(value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize) {

        Map<String, Object> param = new HashMap<>();
        if (StringUtils.isNotBlank(clientId)) {
            param.put("LIKE_clientId", clientId);
        }
        if (StringUtils.isNotBlank(clientName)) {
            param.put("LIKE_clientName", clientName);
        }
        if (StringUtils.isNotBlank(businessLicenseCode)) {
            param.put("LIKE_businessLicenseCode", businessLicenseCode);
        }
        if (StringUtils.isNotBlank(contactPersonName)) {
            param.put("LIKE_contactPersonName", contactPersonName);
        }
        if (StringUtils.isNotBlank(telephone)) {
            param.put("LIKE_telephone", telephone);
        }

        Map<Integer, CounterParty> counterPartyMap = new HashMap<>();
        if (StringUtils.isNotBlank(partyName) || StringUtils.isNotBlank(partyOrganCode)) {
            Map<String, Object> partyParam = new HashMap<>();
            partyParam.put("LIKE_partyName", partyName);
            partyParam.put("LIKE_partyOrganCode", partyOrganCode);
            List<CounterParty> partyList = counterPartyService.listByCondition(partyParam);
            if (CollectionUtils.isNotEmpty(partyList)) {
                param.put("IN_partyId", StringUtils.join(partyList.stream().map(CounterParty::getId).collect(Collectors.toList()), ","));
            } else {
                return PlatformResponse.successData(Page.empty());
            }
        }

        if (StringUtils.isNotBlank(mobile)) {
            param.put("LIKE_mobile", mobile);
        }
        Page<ArchiveClient> clientPage = archiveService.findClientPage(PageUtil.initPageNo(pageNo), PageUtil.initPageSize(pageSize), param);
        if (CollectionUtils.isNotEmpty(clientPage.getContent())) {
            for (ArchiveClient client : clientPage.getContent()) {
                client.setCounterParty(new CounterParty());
                if (Objects.nonNull(client.getPartyId())) {
                    client.setCounterParty(counterPartyService.findById(client.getPartyId()));
                }
            }
        }
        return PlatformResponse.successData(clientPage);
    }

    /**
     * 根据客户id查询客户信息
     *
     * @param clientId
     * @return
     */
    @GetMapping("/client/info")
    public PlatformResponse<ArchiveClient> findArchiveClientById(@ApiParam(value = "客户编号") @RequestParam(required = true) String clientId) {
        ArchiveClient client = archiveService.findClientById(clientId);
        client.setCounterParty(new CounterParty());
        if (Objects.nonNull(client.getPartyId())) {
            CounterParty counterParty = counterPartyService.findById(client.getPartyId());
            if (Objects.nonNull(counterParty)) {
                client.setCounterParty(counterParty);
            }
        }
        return PlatformResponse.successData(client);
    }

    /**
     * 根据客户id查询客户目录
     *
     * @param clientId
     * @return
     */
    @GetMapping("/client/dir")
    public PlatformResponse<List<TreeDto>> findArchiveDirClientByClientId(@ApiParam(value = "客户编号") @RequestParam(required = true) String clientId) {
        TreeDto treeDto = archiveService.buildChildrenArchiveDirClientByClientId(clientId);
        if (Objects.nonNull(treeDto)) {
            return PlatformResponse.successData(Lists.newArrayList(treeDto));
        }
        return PlatformResponse.successData(new ArrayList<>());
    }

    /**
     * 根据客户目录编号查询目录下的文件信息
     *
     * @param clientDirId
     * @return
     */
    @GetMapping("/client/file")
    public PlatformResponse<List<ArchiveFileInfo>> findArchiveFileInfoByClientDirId(@ApiParam(value = "客户目录编号") @RequestParam(required = false) Integer clientDirId) {
        return PlatformResponse.successData(archiveService.findArchiveFileInfoByClientDirId(clientDirId));
    }

    /**
     * 查询未关联目录的文件
     *
     * @param clientId
     * @return
     */
    @GetMapping("/client/file/noRelate")
    public PlatformResponse<List<ArchiveFileInfo>> findNoRelatedArchiveFileInfoByClientId(@ApiParam(value = "客户id") @RequestParam(required = true) String clientId) {
        return PlatformResponse.successData(archiveService.findNoRelatedArchiveFileInfoByClientId(clientId));
    }


    /**
     * 保存上传文件的关联信息
     *
     * @param dto
     * @return
     */
    @PostMapping("/client/file/create/relate")
    public PlatformResponse<?> saveFileRelate(@RequestBody ArchiveFileDto dto) {
        archiveService.saveClientFile(dto);
        return PlatformResponse.successData("关联成功");
    }

    /**
     * 更新客户信息
     *
     * @param client
     * @return
     */
    @PostMapping("/client/update")
    public PlatformResponse<?> clientUpdate(@RequestBody ArchiveClient client) {
        return PlatformResponse.successData(archiveService.updateArchiveClientById(client));
    }

    /**
     * 手动删除文件
     *
     * @param fileId
     * @return
     */
    @GetMapping("/file/delete")
    public PlatformResponse<?> fileDelete(@ApiParam(value = "文件id") @RequestParam(required = true) Integer fileId) {
        archiveService.deleteArchiveFile(fileId);
        return PlatformResponse.success();
    }

    /**
     * 文件归档
     *
     * @param file
     * @return
     */
    @PostMapping("/file/archivist")
    public PlatformResponse<?> archivist(@RequestBody ArchiveFileInfo file) {
        archiveService.archivist(file.getFileId());
        return PlatformResponse.success();
    }

    /**
     * 导出接口不分页
     *
     * @param
     * @param response
     * @return
     * @throws IOException
     */
    @PostMapping("/client/export")
    public byte[] export(@ApiParam(value = "客户编号") @RequestParam(required = false) String clientId,
                         @ApiParam(value = "客户名称") @RequestParam(required = false) String clientName,
                         @ApiParam(value = "营业执照编码") @RequestParam(required = false) String businessLicenseCode,
                         @ApiParam(value = "联系人姓名") @RequestParam(required = false) String contactPersonName,
                         @ApiParam(value = "联系人电话") @RequestParam(required = false) String telephone,
                         @ApiParam(value = "联系人手机") @RequestParam(required = false) String mobile,
                         @ApiParam(value = "交易对手方名称") @RequestParam(required = false) String partyName,
                         @ApiParam(value = "交易对手方组织机构代码") @RequestParam(required = false) String partyOrganCode,
                         HttpServletResponse response) throws IOException {

        response.setHeader("Content-Disposition", "attachment;" + "filename=" + URLEncoder.encode(ReportFileConfigEnum.ARCHIVE_CLIENT_EXPORT.getFileName(), "UTF-8"));

        Map<String, Object> documentParam = new HashMap<>();
        if (StringUtils.isNotBlank(clientId)) {
            documentParam.put("LIKE_clientId", clientId);
        }
        if (StringUtils.isNotBlank(clientName)) {
            documentParam.put("LIKE_clientName", clientName);
        }
        if (StringUtils.isNotBlank(businessLicenseCode)) {
            documentParam.put("LIKE_businessLicenseCode", businessLicenseCode);
        }
        if (StringUtils.isNotBlank(contactPersonName)) {
            documentParam.put("LIKE_contactPersonName", contactPersonName);
        }
        if (StringUtils.isNotBlank(telephone)) {
            documentParam.put("LIKE_telephone", telephone);
        }

        if (StringUtils.isNotBlank(partyName)) {
            documentParam.put("LIKE_partyName", partyName);
        }

        if (StringUtils.isNotBlank(partyOrganCode)) {
            documentParam.put("LIKE_partyOrganCode", partyOrganCode);
        }

        if (StringUtils.isNotBlank(mobile)) {
            documentParam.put("LIKE_mobile", mobile);
        }
        Page<ArchiveClient> clientPage = archiveService.findClientPage(PageUtil.initPageNo(1), PageUtil.initPageSize(3000), documentParam);

        if (Objects.isNull(clientPage) || CollectionUtils.isEmpty(clientPage.getContent())) {
            return null;
        }

        List<ArchiveExcelDto> resList = Lists.newArrayList();
        for (ArchiveClient info : clientPage.getContent()) {
            ArchiveExcelDto archiveExcelDto = new ArchiveExcelDto();
            BeanUtils.copyProperties(info, archiveExcelDto);
            //10-股衍产品-12股衍机构
            if (StringUtils.isNotBlank(info.getClientType())) {
                if (info.getClientType().equals("10")) {
                    archiveExcelDto.setClientType("股衍产品");
                } else if (info.getClientType().equals("12")) {
                    archiveExcelDto.setClientType("股衍机构");
                }
            }
            resList.add(archiveExcelDto);
        }

        return ReportFileUtil.export(resList, ReportFileConfigEnum.ARCHIVE_CLIENT_EXPORT);
    }

    /**
     * 查询机构客户的客户信息汇总表-报表
     *
     * @return
     */
    @PostMapping("/client/org/page")
    public PlatformResponse<Page<ArchiveClientOrgDto>> findOrgClientPage(@RequestBody CounterPartyQueryDto dto) {
        Page<ArchiveClientOrgDto> clientPage = archiveService.findOrgClientPage(dto.getPartyName(), dto.getPartyOrganCode(), dto.getPageNo(), dto.getPageSize());
        return PlatformResponse.successData(clientPage);
    }


    /**
     * 暂未交易的产品清单-报表
     *
     * @return
     */
    @PostMapping("/noTradeProduct/page")
    public PlatformResponse<Page<ArchiveClient>> listNoTradeProduct(@RequestBody YspCustomerQueryDto dto) {

        Map<String, Object> param = new HashMap<>();
        if (StringUtils.isNotBlank(dto.getClientId())) {
            param.put("LIKE_clientId", dto.getClientId());
        }
        if (StringUtils.isNotBlank(dto.getClientName())) {
            param.put("LIKE_clientName", dto.getClientName());
        }
        param.put("EQ_clientType", "10");
        param.put("ISNULL_partyId", "NULL");
        Page<ArchiveClient> clientPage = archiveService.findClientPage(PageUtil.initPageNo(dto.getPageNo()), PageUtil.initPageSize(dto.getPageSize()), param);
        return PlatformResponse.successData(clientPage);
    }

    /**
     * 查询机构客户的客户信息汇总表-报表-导出
     *
     * @param dto
     * @param response
     * @return
     * @throws IOException
     */
    @PostMapping("/client/org/export")
    public byte[] orgClientPageExport(@RequestBody CounterPartyQueryDto dto, HttpServletResponse response) throws IOException {

        response.setHeader("Content-Disposition", "attachment;" + "filename=" + URLEncoder.encode(ReportFileConfigEnum.ORG_CLIENT_EXPORT.getFileName(), "UTF-8"));
        Page<ArchiveClientOrgDto> clientPage = archiveService.findOrgClientPage(dto.getPartyName(), dto.getPartyOrganCode(), PageUtil.initPageNo(1), PageUtil.initPageSize(3000));
        if (Objects.isNull(clientPage) || CollectionUtils.isEmpty(clientPage.getContent())) {
            return null;
        }
        List<OrgClientExcelDto> resList = Lists.newArrayList();
        for (ArchiveClientOrgDto info : clientPage.getContent()) {
            OrgClientExcelDto excelDto = new OrgClientExcelDto();
            BeanUtils.copyProperties(info, excelDto);
            if (StringUtils.isNotBlank(excelDto.getClientName())) {
                excelDto.setClientName(excelDto.getClientName().replaceAll(",", "\r\n"));
            }
            if (StringUtils.isNotBlank(excelDto.getClientId())) {
                excelDto.setClientId(excelDto.getClientId().replaceAll(",", "\r\n"));
            }

            resList.add(excelDto);
        }
        return ReportFileUtil.export(resList, ReportFileConfigEnum.ORG_CLIENT_EXPORT);
    }

    /**
     * 暂未交易的产品清单-报表-导出
     *
     * @param dto
     * @param response
     * @return
     * @throws IOException
     */
    @PostMapping("/noTradeProduct/export")
    public byte[] noTradeProductExport(@RequestBody YspCustomerQueryDto dto, HttpServletResponse response) throws IOException {

        response.setHeader("Content-Disposition", "attachment;" + "filename=" + URLEncoder.encode(ReportFileConfigEnum.NO_TRADE_CLIENT_EXPORT.getFileName(), "UTF-8"));
        Map<String, Object> param = new HashMap<>();
        if (StringUtils.isNotBlank(dto.getClientId())) {
            param.put("LIKE_clientId", dto.getClientId());
        }
        if (StringUtils.isNotBlank(dto.getClientName())) {
            param.put("LIKE_clientName", dto.getClientName());
        }
        param.put("EQ_clientType", "10");
        param.put("ISNULL_partyId", "NULL");
        Page<ArchiveClient> clientPage = archiveService.findClientPage(PageUtil.initPageNo(1), PageUtil.initPageSize(3000), param);
        if (Objects.isNull(clientPage) || CollectionUtils.isEmpty(clientPage.getContent())) {
            return null;
        }
        List<NoTraderClientExcelDto> resList = Lists.newArrayList();
        for (ArchiveClient info : clientPage.getContent()) {
            NoTraderClientExcelDto excelDto = new NoTraderClientExcelDto();
            BeanUtils.copyProperties(info, excelDto);
            resList.add(excelDto);
        }
        return ReportFileUtil.export(resList, ReportFileConfigEnum.NO_TRADE_CLIENT_EXPORT);
    }



    /*@Resource
    private ApplicationContext applicationContext;
    @GetMapping("/test")
    public PlatformResponse<?> test(@ApiParam(value = "文件id") @RequestParam(required = true) String requestId) {
        archiveService.autoDownLoadOperateMattersOaFile(requestId);
        ArchiveUserSynEvent archiveUserSynEvent = new ArchiveUserSynEvent("CF20122401");
        archiveUserSynEvent.setClientType("10");
        archiveUserSynEvent.setClientName("财富证券");
        archiveUserSynEvent.setClientId("CF20122401");
        applicationContext.publishEvent(archiveUserSynEvent);
        return PlatformResponse.success();
    }*/
}
